package com.dts.evaluate.ui.view;

/**
 * Created by user on 2016/9/23.
 */


import android.content.Context;
import android.hardware.Camera;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.dts.evaluate.callback.MyPictureCallback;
import com.dts.evaluate.utils.LogUtil;
import com.dts.evaluate.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Timer;
import java.util.TimerTask;


public class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.PictureCallback {
    private SurfaceHolder holder;
    private Camera camera;
    private boolean af;
    private MyPictureCallback myPictureCallback;

    public CameraView(Context context) {//构造函数
        super(context);
        init();
    }

    public CameraView(Context context, AttributeSet attributes) {//构造函数
        super(context,attributes);
        init();

    }

    private void init(){
        holder = getHolder();//生成Surface Holder
        holder.addCallback(this);

        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//指定Push Buffer
    }




    @Override
    public void surfaceCreated(SurfaceHolder holder) {//Surface生成事件的处理
        try {
            //camera = Camera.open();//摄像头的初始化
            int num = Camera.getNumberOfCameras();
            for (int i = 0; i < num; i++) {
                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    camera = Camera.open(i);
                    camera.setPreviewDisplay(holder);
                    return;
                }
            }

            camera = Camera.open();
            camera.setPreviewDisplay(holder);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {//Surface改变事件的处理
        try {
            Camera.Parameters parameters = camera.getParameters();
            parameters.setPreviewSize(width, height);
            camera.setParameters(parameters);//设置参数
            camera.startPreview();//开始预览
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {//Surface销毁时的处理
        try {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release();
            camera =null;
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {//屏幕触摸事件
        try {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {//按下时自动对焦
                camera.autoFocus(null);
                af =true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP & af ==true) {//放开后拍照
                camera.takePicture(null, null, this);
                ToastUtils.show(getContext(),"拍照成功");
                af =false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 照相
     */
    public void startTakePicture(final String fileName, final MyPictureCallback callback){

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    camera.autoFocus(null);
                    camera.takePicture(null, null, new Camera.PictureCallback() {
                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                            File dir  = new File("/sdcard/evaluate");
                            if(!dir.exists()){
                                dir.mkdir();
                            }

                            String name = fileName + ".jpg";
                            File file = new File(dir,name);
                            String path = file.getAbsolutePath();
                            try {
                                data2file(data, path);
                                callback.callback(path);
                            } catch (Exception e) {
                                e.printStackTrace();
                                LogUtil.v("拍照异常1"+e.getMessage());
                            }
                        }
                    });
                }catch (Exception e){
                   // e.printStackTrace();
                    LogUtil.v("拍照异常2"+e.getMessage());
                }
            }
        }, 500);

    }


    @Override
    public void onPictureTaken(byte[] data, Camera camera) {//拍摄完成后保存照片
        try {
            String path = Environment.getExternalStorageDirectory() +"/test.jpg";
            data2file(data, path);
        } catch (Exception e) {
        }
        camera.startPreview();
    }

    private void data2file(byte[] w, String fileName) throws Exception {//将二进制数据转换为文件的函数
        FileOutputStream out =null;
        try {
            out =new FileOutputStream(fileName);
            out.write(w);
            out.close();
        } catch (Exception e) {
            if (out !=null)
                out.close();
            throw e;
        }
    }


}